package com.qf.sms.service.impl;

import com.qf.base.dto.sms.SmsDTO;
import com.qf.sms.dao.SmsHisDao;
import com.qf.sms.model.SmsHis;
import com.qf.sms.model.SmsHisExample;
import com.qf.sms.service.SmsService;
import com.qf.sms.util.TencentSmsUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.sms.service.impl
 * @Description:
 * @Date 2022/8/1 19:29
 */
@Service
public class SmsServiceImpl implements SmsService {

    public static final int MAX_TIME = 1000*60*50;

    @Resource
    private SmsHisDao smsHisDao;

    @Override
    public int sendSms(String phoneNo, String code, int typeId) {
        //发
        boolean sendResult = TencentSmsUtil.send(phoneNo, code);

        if (sendResult){
            //存
            SmsHis smsHis = new SmsHis();
            smsHis.setPhoneNo(phoneNo);
            smsHis.setCode(code);
            smsHis.setTypeId(typeId);
            smsHis.setTime(System.currentTimeMillis());
            int result = smsHisDao.insertSelective(smsHis);
            return result;
        } else {
            return 0;
        }
    }

    @Override
    public int checkSms(String phoneNo, String code, int typeId) {
        //查询条件
        SmsHisExample smsHisExample = new SmsHisExample();
        SmsHisExample.Criteria criteria = smsHisExample.createCriteria();
        criteria.andPhoneNoEqualTo(phoneNo);
        criteria.andTypeIdEqualTo(typeId);
        //设置查询的排序方式
        smsHisExample.setOrderByClause("`time` desc");
        List<SmsHis> smsHis = smsHisDao.selectByExample(smsHisExample);
        if (smsHis != null && smsHis.size() > 0){
            //查到了
            SmsHis sms = smsHis.get(0);
            if (sms.getCode().equals(code)){
                //验证码正确
                //判断是否过期
                if (System.currentTimeMillis() - sms.getTime() > MAX_TIME ){
                    //过期了
                    return 1;
                } else {
                    //没过期
                    return 0;
                }
            } else {
                //验证码错误
                return 2;
            }
        } else {
            return 2;
        }
    }
}
